package com.hainingtong.core.filter;

import com.google.gson.Gson;
import com.hainingtong.core.config.JwtProperties;
import com.hainingtong.core.exception.TokenInvalidException;
import com.hainingtong.core.shiro.token.JwtToken;
import com.hainingtong.core.util.JwtUtil;
import com.hainingtong.core.util.Result;
import com.hainingtong.core.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class JwtFilter extends BasicHttpAuthenticationFilter {
    @Autowired
    private JwtProperties jwtProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 执行登录认证(如果请求头带有token的话)
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("JwtFilter-->>>isAccessAllowed-Method:init()");
        //如果请求头不存在token,则可能是执行登陆操作或是游客状态访问
        if (isLoginAttempt(request, response)) {
            // 返回 true 表示 直接放行，不去执行token登录操作
            // 返回 false 则所有不带token请求 jwt 过滤器处理的url 会直接报错
            return true;
        }
        //如果存在,则进入executeLogin方法执行登入,检查token 是否正确
        // 返回 false的话 就不会继续往下执行权限判断的部分
        return executeLogin(request, response);
    }

    /**
     * 判断用户是否是登入,检测headers里是否包含token字段
     *
     * @param request
     * @param response
     * @return 返回true表示，访问的是登录接口 或者 没有带 token
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        log.info("JwtFilter-->>>isLoginAttempt-Method:init()");
        HttpServletRequest req = (HttpServletRequest) request;
        if (antPathMatcher.match(this.getLoginUrl(), req.getRequestURI())) {
            return true;
        }
        String token = req.getHeader(jwtProperties.getTokenName());
        return token == null;
    }

    /**
     * 重写AuthenticatingFilter的executeLogin方法丶执行登陆操作
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        log.info("JwtFilter-->>>executeLogin-Method:init()");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(jwtProperties.getTokenName());//Access-Token
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入,如果错误他会抛出异常并被捕获, 反之则代表登入成功,返回true
        try {
            getSubject(request, response).login(jwtToken);
        }catch (Exception e){
            log.warn("token认证出错：{}", e.getMessage());
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            httpServletResponse.setStatus(HttpStatus.OK.value());
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            try (PrintWriter writer = httpServletResponse.getWriter()) {
                writer.write(new Gson().toJson(Result.error(ResultCode.ERROR_TOKEN_INVALID)));
                writer.flush();
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
            return false;
        }
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("JwtFilter-->>>preHandle-Method:init()");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;// 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;  // 返回false就不会继续往下执行了，直接返回给客户端了
        }
        return super.preHandle(request, response);
    }
}